package com.example.readroomforpaging3.viewmodel

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.example.readroomforpaging3.network.NetworkCreator
import com.example.readroomforpaging3.paging.ArticleRemoteMediator
import com.example.readroomforpaging3.room.ArticleDatabase

class ArticleViewModel(context: Context) : ViewModel() {

    companion object {
        const val DEFAULT_PAGE_INDEX = 0
        const val DEFAULT_PAGE_SIZE = 20
    }

    private val pagingSourceFactory = {
        // 数据源，要求返回的是 PagingSource 类型对象
        ArticleDatabase.getDatabase(context).articleDao().getArticle()
    }

    @ExperimentalPagingApi
    val articlePage by lazy {
        Pager(
                PagingConfig(
                        // 每页显示的数据的大小。对应 PagingSource 里 LoadParams.loadSize
                        pageSize = DEFAULT_PAGE_SIZE,

                        // 预刷新的距离，距离最后一个 item 多远时加载数据，默认为 pageSize
                        prefetchDistance = 3,

                        // 初始化加载数量，默认为 pageSize * 3
                        initialLoadSize = 60,

                        // 一次应在内存中保存的最大数据，默认为 Int.MAX_VALUE
                        maxSize = 200
                ),
                pagingSourceFactory = pagingSourceFactory,
                remoteMediator = ArticleRemoteMediator(NetworkCreator.articleApi, ArticleDatabase.getDatabase(context))
        ).flow.cachedIn(viewModelScope) // 最后构造的和外部交互对象，有 flow 和 liveData 两种
    }
}